package mo.org.cm309.shoppingcart.filter;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



import mo.org.cm309.shoppingcart.entity.User;

public class LoginFilter implements Filter {
	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain filterChain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest request   = (HttpServletRequest)req;
		HttpServletResponse response = (HttpServletResponse)resp;
		
		User user = (User)request.getSession().getAttribute("loginUser");
		if (user == null){
			StringBuffer sUrl = new StringBuffer("");
			 if (request.getRequestURI() != null) {
				 sUrl.append(URLEncoder.encode(request.getRequestURI(), "UTF-8"));
			 }
			 if (request.getQueryString() != null) {
				 sUrl.append("?");
				 sUrl.append(URLEncoder.encode(request.getQueryString(), "UTF-8"));
			 }
			 String retUrl = (URLDecoder.decode(sUrl.toString(), "UTF-8")).substring(6);
			 System.out.println("URL=============================" + retUrl);
			 filterChain.doFilter(request, response);
		}
	}
}
